var express = require("express");
var router = express.Router();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const uuid = require("uuid");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/img/cover");
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = uuid.v4();
    cb(null, uniqueSuffix + path.extname(file.originalname));
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fieldSize: 5 * 1024 * 1024 * 1024,
  },
});

/*
 * 获取文章主题
 * 返回值： [{subject_id: int, name: '' }, ...]
 */
router.get("/subject", async (req, res) => {
  const subject_list = await prisma.article_subject.findMany();
  res.json(subject_list);
});

// 查询数据库
async function getList(condition, user_id) {
  const article_list = await prisma.article_all.findMany({
    where: condition,
    orderBy: {
      time: "desc",
    },
    select: {
      article_id: true,
      user_id: true,
      subject_id: true,
      title: true,
      abstract: true,
      cover: true,
      time: true,
      views: true,
      state: true,

      user_all: {
        select: {
          user_name: true,
        },
      },
      num_collect: {
        select: {
          num: true,
        },
      },
      num_like: {
        select: {
          num: true,
        },
      },
      article_subject: {
        select: {
          name: true,
        },
      },
    },
  });
  const len = article_list.length;
  for (let i = 0; i < len; i++) {
    const article_id = article_list[i].article_id;
    const like = await prisma.user_like.findMany({
      where: {
        topic_id: article_id,
        topic_type: 1,
        user_id: user_id,
      },
    });
    const collect = await prisma.user_collect.findMany({
      where: {
        topic_id: article_id,
        topic_type: 1,
        user_id: user_id,
      },
    });
    article_list[i].isLike = like.length >= 1;
    article_list[i].isCollect = collect.length >= 1;
  }
  return article_list;
}

/*
 * 获取文章列表
 * state:        必要, 0：已发布; 1：未发布, 草稿箱
 * subject_id：  非必要, 主题id
 * 返回值：[] 文章记录数组, 不包含文章内容
 */
router.get("/list", async (req, res) => {
  let condition = {};
  condition.state = parseInt(req.query.state);
  if (req.query.subject_id != null) condition.subject_id = parseInt(req.query.subject_id);
  const article_list = await getList(condition, req.auth.user.user_id);

  res.json(article_list);
});

/*
 * 获取当前登录用户的文章列表
 * state:        必要, 0：已发布; 1：未发布, 草稿箱
 * subject_id：  非必要, 主题id
 * 返回值：[] 文章记录数组, 不包含文章内容
 */
router.get("/user-list", async (req, res) => {
  let condition = {};
  condition.user_id = req.auth.user.user_id;
  condition.state = parseInt(req.query.state);
  if (req.query.subject_id != null) condition.subject_id = parseInt(req.query.subject_id);

  const article_list = await getList(condition, req.auth.user.user_id);

  res.json(article_list);
});


/*
 * 获取当前登录用户收藏的文章列表
 * 返回值：[] 文章记录数组, 包含点赞数、收藏数, 不包含文章内容
 */
router.get("/user-collect", async (req, res) => {
  const collectId = await prisma.user_collect.findMany({
    where: {
      user_id: req.auth.user.user_id,
      topic_type: 1, //文章
    }
  });
  let id_list = []
  collectId.forEach((item) => {
    id_list.push(item.topic_id)
  })
  let condition = {
    article_id: { in: id_list },
  };
  const article_list = await getList(condition, req.auth.user.user_id);

  res.json(article_list);
});

/*
 * 获取文章详细内容，浏览量 + 1
 * 参数：article_id
 * 返回值： {} 文章记录对象
 */
router.get("/content", async (req, res) => {
  const { article_id } = req.query;

  // 浏览量 + 1
  const article_update = await prisma.article_all.updateMany({
    where: { article_id: article_id },
    data: {
      views: {
        increment: 1,
      },
    },
  });

  // 获取数据
  const article = await prisma.article_all.findFirst({
    where: { article_id: article_id },
    include: {
      user_all: {
        select: {
          user_name: true,
        },
      },
      num_collect: {
        select: {
          num: true,
        },
      },
      num_like: {
        select: {
          num: true,
        },
      },
      article_subject: {
        select: {
          name: true,
        },
      },
    },
  });

  const like = await prisma.user_like.findMany({
    where: {
      topic_id: article_id,
      topic_type: 1,
      user_id: req.auth.user.user_id,
    },
  });
  const collect = await prisma.user_collect.findMany({
    where: {
      topic_id: article_id,
      topic_type: 1,
      user_id: req.auth.user.user_id,
    },
  });
  article.isLike = like.length >= 1;
  article.isCollect = collect.length >= 1;

  res.json(article);
});

/*
 * 保存文章
 * title：     必要, 标题
 * content:    必要, 内容
 * abstract：  发布文章时必要, 保存为草稿时非必要; 摘要
 * state:      必要, 0：已发布; 1：未发布, 草稿箱
 * cover:      非必要, 封面图片文件
 * subject_id: 非必要, 主题id
 */
router.post("/save", upload.single("cover"), async (req, res) => {
  const { title, content, abstract, state } = req.body; //必传参数
  let data = { title: title, content: content, state: parseInt(state) };
  data.article_id = uuid.v4();
  data.user_id = req.auth.user.user_id;
  data.time = new Date().getTime().toString();
  data.views = 0;
  if (req.body.abstract != null) data.abstract = req.body.abstract;
  if (req.body.subject_id != null) data.subject_id = parseInt(req.body.subject_id);
  if (req.file != null) data.cover = "http://localhost:3000/img/cover/" + req.file.filename;

  const num_like = await prisma.num_like.create({
    data: { topic_id: data.article_id, topic_type: 1, num: 0 },
  });
  data.num_like_id = num_like.id;

  const num_collect = await prisma.num_collect.create({
    data: { topic_id: data.article_id, topic_type: 1, num: 0 },
  });
  data.num_collect_id = num_collect.id;

  //插入数据库
  const article = await prisma.article_all.create({
    data: data,
  });

  res.json(article);
});

/*
 * 修改文章
 * article_id: 必要, 文章id
 * title：     必要, 标题
 * content:    必要, 内容
 * abstract：  发布文章时必要, 保存为草稿时非必要; 摘要
 * state:      必要, 0：已发布; 1：未发布, 草稿箱
 * cover:      非必要, 封面图片文件
 * subject_id: 非必要, 主题id
 */
router.post("/update", upload.single("cover"), async (req, res) => {
  const { article_id, title, content, state } = req.body; //必传参数
  let data = { title: title, content: content, state: parseInt(state) };
  data.time = new Date().getTime().toString();
  if (req.body.abstract != null) data.abstract = req.body.abstract;
  if (req.body.subject_id != null) data.subject_id = parseInt(req.body.subject_id);

  //如果封面发生改变, 则删除原封面
  if (req.file != null) {
    //获取原封面路径
    const old_article = await prisma.article_all.findFirst({
      where: {
        article_id: article_id,
      },
    });
    if (old_article.cover != null) {//如果旧封面存在
      let old_cover_path = "public" + old_article.cover.substring(21);
      //删除
      if (fs.existsSync(old_cover_path)) {
        fs.unlink(old_cover_path, (err) => {
          // 如果没有错误，则文件已成功删除
          if (!err) console.log("File deleted!");
        });
      }
    }
    //设置新封面路径
    data.cover = "http://localhost:3000/img/cover/" + req.file.filename;
  }

  //更新数据库
  const newArticle = await prisma.article_all.update({
    where: { article_id: article_id },
    data: data,
  });

  res.json(newArticle);
});

/*
 * 删除文章
 * article_id: 待删除文章id
 */
router.delete("/delete", async (req, res) => {
  const { article_id } = req.query;

  //删除文章
  const article = await prisma.article_all.deleteMany({
    where: {
      article_id: article_id,
    },
  });

  //删除评论
  const comment = await prisma.user_comment.deleteMany({
    where: {
      topic_id: article_id,
      topic_type: 1
    }
  })

  res.json(article);
});

module.exports = router;
